package main

import (
	"flag"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"log"
)

type config struct {
	v *viper.Viper
}

// todo https://studygolang.com/articles/14249
// 1. 从command Line中读取配置
// 标准包的 flag -> pflag -> viper
// go run example02.go --ip=192.168.0.120 --port=444 --mode=DEBUG
func LoadConfigFromCommandLine() error {
	flag.String("mode", "RUN", "please input the mode: RUN or DEBUG")
	pflag.Int("port", 1080, "please input the listen port")
	pflag.String("ip", "127.0.0.1", "please input the bind ip")
	//获取标准包的flag
	pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
	pflag.Parse()

	// BindFlag
	// 在pflag.Init key后面使用
	// pflag 的数据绑定到 viper 上
	viper.BindPFlag("port", pflag.Lookup("port"))
	log.Printf("set port: %d", viper.GetInt("port"))

	// bind all
	viper.BindPFlags(pflag.CommandLine)
	log.Printf("set ip: %s", viper.GetString("ip"))
	return nil
}
func initLoadConfigFromCommandLine() {
	err := LoadConfigFromCommandLine()
	if err != nil {
		panic(err)
	}
	log.Println("init Load config from command line successful.")
}

func init() {
	initLoadConfigFromCommandLine()
}

func main() {

}
